package org.shagin.jfin.ui.budget.item;

import java.util.HashMap;
import java.util.Map;

import org.shagin.jfin.core.Debug;
import org.shagin.jfin.ui.budget.item.impl.AbstractBudgetItemView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class BudgetItemViewRegistry.
 */
public class BudgetItemViewRegistry {

    private static final Logger log = LoggerFactory
            .getLogger(BudgetItemViewRegistry.class);

    private Map<Class<?>, Class<? extends AbstractBudgetItemView>> itemViewClassesRegistry = new HashMap<Class<?>, Class<? extends AbstractBudgetItemView>>();

    /**
     * Instantiates a new budget item view registry.
     */
    public BudgetItemViewRegistry() {

    }

    /**
     * Gets the item.
     * 
     * @param clazz the clazz
     * @return the item
     */
    public AbstractBudgetItemView findAndCreate(Class<?> objClass) {
        Debug.traceEnter(log, Debug.toString(objClass));
        AbstractBudgetItemView result = null;
        if (objClass != null) {
            result = newInstance(findViewClass(objClass));
        }
        return result;
    }

    /**
     * Find class.
     * 
     * @param clazz the clazz
     * @return the class
     */
    public Class<? extends AbstractBudgetItemView> findViewClass(
            Class<?> objClass) {
        Debug.traceEnter(log, Debug.toString(objClass));
        Class<? extends AbstractBudgetItemView> result = null;
        if (objClass != null) {
            result = itemViewClassesRegistry.get(objClass);
        }
        return result;
    }

    /**
     * New instance.
     * 
     * @param clazz the clazz
     * @return the abstract budget item view
     */
    public AbstractBudgetItemView newInstance(
            Class<? extends AbstractBudgetItemView> viewClass) {
        Debug.traceEnter(log, Debug.toString(viewClass));
        AbstractBudgetItemView result = null;
        if (viewClass != null)
            try {
                log.trace("Creating instance " + viewClass.getName());
                result = viewClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        return result;
    }

    /**
     * Register.
     * 
     * @param objClass the obj class
     * @param viewClass the view class
     */
    public void register(Class<?> objClass,
            Class<? extends AbstractBudgetItemView> viewClass) {
        Debug.traceEnter(log, objClass, viewClass);
        itemViewClassesRegistry.put(objClass, viewClass);
    }

}
